import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        return 'Труба обсадная ТЭСЦ-3'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        try:
            product = row["Первичный продукт"]
            carving = row["Тип резьбы <Производство>"]
            strength_class = row["Класс прочности <Производство>"]
            steel_mark = row["Марка стали <Производство>"]
            diametr = row["Диаметр, мм <Производство>"]
            carving_type = consolidator.scalar_in_guid("Резьба",f"`Исх резьба`=='{carving}'","Результ Резьба")
            if pd.isna(carving) or pd.isna(carving_type): carving_type="БР"
            # strength_group = consolidator.scalar_in_guid("Группа по классу прочности для труб",f"`Марка стали`=='{strength_class}' or `Марка стали`=='{steel_mark}'","Группа прочности")
            # if pd.isna(strength_group): strength_group="ПD"
            strength_group = consolidator.strength_group_by_steel(strength_class,steel_mark)
            diametr_type = consolidator.nearest_in_guid("Параметры по Продукту ТЭСЦ-5",
                f"`Производство`=='Труба обсадная ТЭСЦ-5' and `Продукт`=='{product}'",
                "Доп параметр1",
                diametr,
                "Доп параметр1")
            diametr_type_s = str(diametr_type).replace(".0","")
            print(f"product: {product}; carving: {carving}; strength_group: {strength_group}; diametr_type: {diametr_type_s}")
            product_up=f"{product}{diametr_type_s} ГО {strength_group} {carving_type}"
            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__pipe_casing_t3__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

